using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Admin.NET.Application.Entity.Business;
using Admin.NET.Core;
using Furion.DependencyInjection;
using Furion.EventBus;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;

namespace Admin.NET.Application.EventBus;

/// <summary>
/// 站内信通知消息订阅，类型0
/// </summary>
public class InternalMessageEventSubscribe : IEventSubscriber, ISingleton, IPrivateDependency
{
	private readonly IServiceProvider _serviceProvider;

	public InternalMessageEventSubscribe(IServiceProvider serviceProvider)
	{
		_serviceProvider = serviceProvider;
	}

	/// <summary>
	/// 发送通知站内信（自定义账单催缴）
	/// </summary>
	/// <param name="context"></param>
	/// <returns></returns>
	[EventSubscribe("0:SendBillNotice")]
	[EventSubscribe("0:SendGateNotice")]
	[EventSubscribe("0:SendPaymentNotice")]
	[EventSubscribe("0:SendEarlyWarningNotice")]
	public async Task SendNotice(EventHandlerExecutingContext context)
	{
		using IServiceScope scope = _serviceProvider.CreateScope();
		SqlSugarRepository<OwnerNotice> _rep = scope.ServiceProvider.GetRequiredService<SqlSugarRepository<OwnerNotice>>();
		EventPayload payload = (EventPayload)context.Source.Payload;
		BillNoticePayload owners = JsonConvert.DeserializeObject<BillNoticePayload>(payload.Data);
		List<OwnerNotice> ownerNotices = owners.Owners.Select((Owner s) => new OwnerNotice
		{
			Content = owners.Body,
			OwnerId = s.Id,
			Remark = owners.Remark,
			Title = owners.Subject,
			TenantId = payload.TenantId,
			CreateUserId = payload.UserId,
			Status = 0,
			Path = owners.Path
		}).ToList();
		await _rep.Context.Insertable(ownerNotices).ExecuteCommandAsync();
	}
}
